package com.rxm.ys.controller;

import com.rxm.ys.Rs;
import com.rxm.ys.entity.User;
import com.rxm.ys.feign.UserClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;

/**
 * @Description
 * @Author FengYi
 * @Date 2020-05-11 17:19
 */
@RestController
public class DemoController {

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${spring.application.name}")
    private String appName;

    @Autowired
    private UserClient userClient;

    @GetMapping("/echo/appName")
    public String echoAppName() {
        //使用 LoadBalanceClient 和 RestTemplate 结合的方式来访问
        ServiceInstance serviceInstance = loadBalancerClient.choose("ys-user");
        String url = String.format("http://%s:%s/print/%s", serviceInstance.getHost(), serviceInstance.getPort(), appName);
        System.out.println("request url:" + url);
        return restTemplate.getForObject(url, String.class);
    }

    @GetMapping("/user/getByCode")
    public Rs<User> getByCode() {
        Rs<User> rs = userClient.getByCode(LocalDateTime.now().toString());
        return rs;
    }
}
